package com.dayuanit.dy15.spider.task;

import com.dayuanit.dy15.spider.dto.ThirdInfoDTO;
import com.dayuanit.dy15.spider.mapper.CommodityMapper;
import com.dayuanit.dy15.spider.mapper.NavigationMapper;
import com.dayuanit.dy15.spider.pool.SpiderThreadPool;
import com.dayuanit.dy15.spider.runnable.BookInfoRunnable;
import com.dayuanit.dy15.spider.util.ApiConnector;
import com.dayuanit.dy15.spider.util.SleepUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 通过第三级导航栏 访问其页面 获取书本的详情连接
 */
@Component
public class BookTask extends BaseTask {

    @Autowired
    private CommodityMapper commodityMapper;

    @Autowired
    private NavigationMapper navigationMapper;

    @Override
    public void doTask() {
        for (ThirdInfoDTO dto : thirdUrls) {
            String thirdUrl = dto.getUrl();
            String html = ApiConnector.get(thirdUrl);
            Document document = Jsoup.parse(html);
            Elements bookAelement = document.select("div.book.book_list.clearfix").select("a");

            bookAelement.forEach(element -> {
                String bookInfoUrl = element.attr("href");
                String bookPrice = element.select("div.bookinfo").select("div.price").first().text();
                if (null == bookPrice || "".equals(bookPrice)) {
                    bookPrice = "10.00";
                }

                bookPrice = bookPrice.replace("￥", "");
                System.out.println(">>>>>>>>书本详情地址：" + bookInfoUrl + " " + bookPrice);

                //通过线程池来处理书本详情
                SpiderThreadPool.bookInfoThreadPool.execute(new BookInfoRunnable(bookInfoUrl, bookPrice, dto.getNavName(), commodityMapper, navigationMapper));
            });

//            break;

            SleepUtil.sleep();
        }
    }
}
